import { world, EquipmentSlot, Player } from "@minecraft/server";
import { utils } from "../..";

/**
 * Define a tool tag.
 * If an item has this tag, it will automatically consume durability.
 */
export class ToolTag {
  /**
   * The tag of the tool.
   */
  tag: string;
  constructor(tag: string) {
    this.tag = tag;
    world.afterEvents.playerBreakBlock.subscribe((event) => {
      const ENTITY = event.player;
      let ITEM = utils.getEquipmentItem(ENTITY);
      if (ITEM?.hasTag(tag)) {
        ENTITY?.getComponent("minecraft:equippable")?.setEquipment(
          EquipmentSlot.Mainhand,
          utils.consumeDurability(ITEM, 1, ENTITY),
        );
      }
    });
    world.afterEvents.entityHitEntity.subscribe((event) => {
      const ENTITY = event.damagingEntity;
      let ITEM = utils.getEquipmentItem(event.damagingEntity);
      if (ITEM?.hasTag(tag)) {
        ENTITY?.getComponent("minecraft:equippable")?.setEquipment(
          EquipmentSlot.Mainhand,
          utils.consumeDurability(
            ITEM,
            2,
            ENTITY instanceof Player ? ENTITY : undefined,
          ),
        );
      }
    });
  }
}

/**
 * Define a tool that will automatically consume durability for it.
 */
export class ToolItem {
  /**
   * The item id of the tool.
   */
  id: string;
  constructor(id: string) {
    this.id = id;
    world.afterEvents.playerBreakBlock.subscribe((event) => {
      const ENTITY = event.player;
      let ITEM = utils.getEquipmentItem(ENTITY);
      if (ITEM?.typeId === id) {
        ENTITY?.getComponent("minecraft:equippable")?.setEquipment(
          EquipmentSlot.Mainhand,
          utils.consumeDurability(ITEM, 1, ENTITY),
        );
      }
    });
    world.afterEvents.entityHitEntity.subscribe((event) => {
      const ENTITY = event.damagingEntity;
      let ITEM = utils.getEquipmentItem(event.damagingEntity);
      if (ITEM?.typeId === id) {
        ENTITY?.getComponent("minecraft:equippable")?.setEquipment(
          EquipmentSlot.Mainhand,
          utils.consumeDurability(
            ITEM,
            2,
            ENTITY instanceof Player ? ENTITY : undefined,
          ),
        );
      }
    });
  }
}
